<template>
  <view class="order-page-bg">
    <view class="order-card">
      <!-- 地址栏 -->
      <!-- 地址栏渲染逻辑优化 -->
      <view class="address-bar" @click="chooseAddress">
        <wd-icon name="location" size="28px" color="#e64340" />
        <view class="address-info">
          <text class="address-name">
            {{ currentAddress ? currentAddress.name : '收货人' }}
          </text>
          <text class="address-detail">
            {{ fullAddress || '请选择收货地址' }}
          </text>
          <text class="address-tel" v-if="currentAddress">
            {{ currentAddress.tel }}
          </text>
        </view>
        <wd-icon name="arrow-right" size="22px" color="#bbb" />
      </view>

      <!-- 商品清单 -->
      <view class="goods-list">
        <view v-for="item in orderGoods" :key="item.id" class="goods-item">
          <image :src="item.thumb_path || item.image || '/static/logo.png'" class="goods-img" mode="aspectFill" />
          <view class="goods-info">
            <text class="goods-title ellipsis">{{ item.title }}</text>
            <view class="goods-meta">
              <text class="goods-count">x{{ item.count }}</text>
              <text class="goods-price">¥{{ item.sell_price }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单详情 -->
      <view class="order-detail-group">
        <view class="order-detail-row">
          <text class="label">订单号</text>
          <text class="value">{{ orderId }}</text>
        </view>
        <view class="order-detail-row">
          <text class="label">下单时间</text>
          <text class="value">{{ orderTime }}</text>
        </view>
        <view class="order-detail-row">
          <text class="label">商品数量</text>
          <text class="value">{{ orderGoods.length }}</text>
        </view>
        <view class="order-detail-row">
          <text class="label">付款方式</text>
          <text class="value">微信支付</text>
        </view>
        <view class="order-detail-row">
          <text class="label">运费险</text>
          <text class="value">赠送</text>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="order-bottom-bar">
      <view class="total-box">
        <text class="total-label">应付：</text>
        <text class="total-price">¥{{ totalPrice }}</text>
      </view>
      <view class="btn-group">
        <button class="cancel-btn" @click="cancelOrder">取消订单</button>
        <button class="pay-btn" @click="commitOrder">立即支付</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

const addressList = ref([])
const orderGoods = ref([])
const orderId = ref('')
const totalPrice = ref(0)
const addressId = ref('')
const orderTime = ref('')
const openid = uni.getStorageSync('openid')

// 地址选择（京东风格可弹窗选择，暂用picker逻辑）
function chooseAddress() {
  // 可跳转到地址管理页面
  uni.navigateTo({ url: '/pages/address/address' })
}

onShow(() => {
  orderGoods.value = uni.getStorageSync('orderGoods') || []
  orderId.value = uni.getStorageSync('orderId') || ''
  totalPrice.value = uni.getStorageSync('orderTotalPrice') || 0
  const now = new Date()
  orderTime.value = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2,'0')}-${now.getDate().toString().padStart(2,'0')} ${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}:${now.getSeconds().toString().padStart(2,'0')}`
  fetchAddressList().then(() => {
    console.log('onShow后 addressId:', addressId.value)
  })
})

const fetchAddressList = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await request({
      url: BASE_URL + 'api/getaddress/',
      method: 'GET',
      header: { token }
    })
    let list = Array.isArray(res.data) ? res.data : res.data.message || []
    addressList.value = list
    console.log('订单页获取到地址列表:', list)
    const selectedId = uni.getStorageSync('selectedAddressId')
    console.log('订单页读取 selectedAddressId:', selectedId)
    if (selectedId) {
      const selectedAddr = list.find(a => a.id == selectedId)
      console.log('订单页查找选中地址:', selectedAddr)
      if (selectedAddr) {
        addressId.value = selectedId
        uni.removeStorageSync('selectedAddressId')
        console.log('订单页使用用户选择的地址:', selectedAddr)
      } else if (list.length > 0) {
        addressId.value = list[0].id
        console.log('订单页 selectedId 无效，选第一个:', list[0])
      } else {
        addressId.value = ''
        console.log('订单页无地址数据')
      }
    } else if (list.length > 0) {
      addressId.value = list[0].id
      console.log('订单页无选择，选第一个:', list[0])
    } else {
      addressId.value = ''
      console.log('订单页无地址数据')
    }
    console.log('订单页最终 addressId:', addressId.value)
  } catch (e) {
    uni.showToast({ title: '获取地址失败', icon: 'none' })
    console.error('订单页获取地址失败:', e)
  }
}

async function commitOrder() {
  if (!addressId.value) {
    uni.showToast({ title: '请选择收货地址', icon: 'none' })
    return
  }
  const token = uni.getStorageSync('token')
  const openid = uni.getStorageSync('openid')
  if (!openid) {
    uni.showToast({ title: 'openid获取失败，请重新登录', icon: 'none' })
    return
  }
  try {
    // 1. 请求后端获取支付参数
    const payRes = await request({
      url: BASE_URL + 'api/wxpay',
      method: 'POST',
      header: {
        token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        openid,
        order_id: orderId.value,
        total_price: totalPrice.value
      }
    })
    console.log('支付接口返回:', payRes)
    // 2. 检查返回
    if (payRes.data && payRes.data.status === 200 && payRes.data.data) {
      const params = payRes.data.data
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: params.timeStamp,
        nonceStr: params.nonceStr,
        package: params.package,
        signType: params.signType,
        paySign: params.paySign,
        success: function (res) {
          // 支付成功后逻辑
          checkPayStatus(orderId.value)
        },
        fail: async function (err) {
          uni.showToast({ title: '支付失败', icon: 'none' })
          // 支付失败时提交订单信息
          try {
            const token = uni.getStorageSync('token')
            // 组装商品id字符串和数量
            const goodsIds = orderGoods.value.map(item => item.id).join(',')
            const number = orderGoods.value.reduce((sum, item) => sum + (item.count || 1), 0)
            const commitRes = await request({
              url: BASE_URL + 'api/commitorder',
              method: 'POST',
              header: {
                token,
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                order_id: orderId.value,
                goods_ids: goodsIds,
                number: number.toString(),
                total_price: totalPrice.value.toString(),
                address_id: addressId.value.toString()
              }
            })
            console.log('提交订单接口返回:', commitRes)
          } catch (e) {
            console.error('提交订单失败:', e)
          }
        }
      })
    } else {
      uni.showToast({ title: payRes.data.message || '支付参数获取失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '支付请求异常', icon: 'none' })
  }
}

// 心跳检测查询支付状态（1分钟内每2秒查一次）
function checkPayStatus(orderId: string, tryCount = 0) {
  const token = uni.getStorageSync('token')
  console.log(`第${tryCount + 1}次轮询支付状态...`)
  uni.request({
    url: BASE_URL + 'api/queryPayOrder',
    method: 'POST', // 改为POST
    header: { 
      token,
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: { order_id: orderId },
    success: (res) => {
      console.log('支付状态接口返回:', res)
      if (res.statusCode === 502) {
        uni.hideLoading()
        uni.showModal({
          title: '支付结果',
          content: '服务器异常，请稍后再试或联系客服。',
          showCancel: false,
          success: () => {
            uni.reLaunch({ url: '/pages/index/index' })
          }
        })
        return
      }
      if (res.data && res.data.status === 200 && res.data.data) {
        console.log('当前支付状态:', res.data.data.pay_status)
        if (res.data.data.pay_status === 'SUCCESS') {
          uni.hideLoading()
          uni.showModal({
            title: '支付结果',
            content: '支付成功！',
            showCancel: false,
            success: () => {
              uni.reLaunch({ url: '/pages/index/index' })
            }
          })
        } else if (tryCount < 29) {
          setTimeout(() => checkPayStatus(orderId, tryCount + 1), 2000)
        } else {
          uni.hideLoading()
          uni.showModal({
            title: '支付结果',
            content: '支付超时，请稍后在订单列表查看。',
            showCancel: false,
            success: () => {
              uni.reLaunch({ url: '/pages/index/index' })
            }
          })
        }
      } else {
        uni.hideLoading()
        uni.showModal({
          title: '支付结果',
          content: res.data.message || '查询支付状态失败',
          showCancel: false,
          success: () => {
            uni.reLaunch({ url: '/pages/index/index' })
          }
        })
      }
    },
    fail: (err) => {
      console.error('支付状态接口请求失败:', err)
      if (tryCount < 29) {
        setTimeout(() => checkPayStatus(orderId, tryCount + 1), 2000)
      } else {
        uni.hideLoading()
        uni.showModal({
          title: '支付结果',
          content: '支付超时，请稍后在订单列表查看。',
          showCancel: false,
          success: () => {
            uni.reLaunch({ url: '/pages/index/index' })
          }
        })
      }
    }
  })
}

// 取消订单并返回购物车
function cancelOrder() {
  uni.removeStorageSync('orderGoods')
  uni.removeStorageSync('orderId')
  uni.removeStorageSync('orderTotalPrice')
  uni.switchTab({ url: '/pages/shopping/shopping' })
}

const currentAddress = computed(() => {
  if (addressList.value.length === 0) return null
  const addr = addressList.value.find(a => a.id == addressId.value)
  return addr || addressList.value[0] || null
})

const fullAddress = computed(() => {
  if (!currentAddress.value) return ''
  // 兼容字段名，按你的实际数据结构调整
  return [
    currentAddress.value.province,
    currentAddress.value.city,
    currentAddress.value.county,
    currentAddress.value.addressDetail || currentAddress.value.detail || ''
  ].filter(Boolean).join(' ')
})
</script>

<style scoped>
.order-page-bg {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;
}
.order-card {
  width: 100vw;
  background: #fff;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding-bottom: 120rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.address-bar {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx 24rpx 24rpx;
  background: #fff7f7;
  border-bottom: 1px solid #f0f0f0;
}
.address-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 18rpx;
}
.address-name {
  font-size: 28rpx;
  color: #e64340;
  font-weight: bold;
}
.address-detail {
  font-size: 24rpx;
  color: #333;
  margin-top: 4rpx;
  line-height: 1.4;
}
.address-tel {
  font-size: 22rpx;
  color: #666;
  margin-top: 2rpx;
}
.goods-list {
  background: #fff;
  padding: 0;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
}
.goods-item {
  display: flex;
  align-items: center;
  padding: 24rpx 24rpx 18rpx 24rpx;
  border-bottom: 1px solid #f0f0f0;
}
.goods-img {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8px;
  margin-right: 18rpx;
  background: #eee;
  object-fit: cover;
}
.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}
.goods-title {
  font-size: 28rpx;
  color: #222;
  font-weight: 500;
  max-width: 80vw;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.goods-meta {
  display: flex;
  align-items: center;
  gap: 18rpx;
}
.goods-count {
  font-size: 24rpx;
  color: #666;
  background: #e9e9e9;
  border-radius: 8px;
  padding: 0 10rpx;
}
.goods-price {
  font-size: 26rpx;
  color: #e64340;
  font-weight: bold;
}
.order-detail-group {
  background: #fff;
  padding: 0 24rpx 24rpx 24rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.order-detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 0;
  border-bottom: 1px solid #f0f0f0;
}
.label {
  font-size: 26rpx;
  color: #666;
}
.value {
  font-size: 26rpx;
  color: #222;
  font-weight: 500;
}
.order-bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 140rpx; /* 原来是100rpx，已加高 */
  z-index: 99;
}
.total-box {
  display: flex;
  align-items: center;
}
.total-label {
  font-size: 28rpx;
  color: #222;
  font-weight: bold;
}
.total-price {
  font-size: 34rpx;
  color: #e64340;
  font-weight: bold;
  margin-left: 8rpx;
}
.btn-group {
  display: flex;
  align-items: center;
  gap: 18rpx;
}
.pay-btn {
  height: 72rpx;
  min-width: 180rpx;
  background: linear-gradient(90deg, #e64340 0%, #ffb347 100%);
  color: #fff;
  border: none;
  border-radius: 36rpx;
  font-size: 30rpx;
  font-weight: bold;
  box-shadow: 0 4px 16px rgba(230,67,64,0.08);
  letter-spacing: 2px;
  transition: background 0.3s;
}
.pay-btn:active {
  background: linear-gradient(90deg, #ffb347 0%, #e64340 100%);
}
.cancel-btn {
  height: 72rpx;
  min-width: 140rpx;
  background: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 36rpx;
  font-size: 28rpx;
  font-weight: bold;
  letter-spacing: 2px;
  margin-right: 0;
  transition: background 0.3s;
}
.cancel-btn:active {
  background: #e0e0e0;
  color: #e64340;
}
.use-btn {
  color: #67C23A;
  margin-left: 15px;
  font-size: 14px;
  cursor: pointer;
}
</style>